import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_buisiness_2006a/bean/cart_info_bean_result.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CartProvider with ChangeNotifier {
  String? cartString = '[]'; //用于保存到sp当中的字符串
  List<CartInfoBeanResult> cartList = []; //从sp中的json翻译过来的数据源,用于提供给页面
  String spKey = "cartInfo";
  bool isAllCheck = true; //用于检查是否全选
  double allPrice = 0; //商品的总价
  num allGoodsCount = 0; //所有选中商品的数量

  //存到sp中的方法
  save(goodsId, goodsName, count, price, imageUrl, isCheck) async {
    SharedPreferences sharedPreferences =
        await SharedPreferences.getInstance(); //拿到sp的实例
    cartString = sharedPreferences.getString(spKey); //从sp中获取持久化数据
    //判断cartString是否为空,为空就说明是第一次添加商品,或者cartInfo被清除了,则赋值一个空的集合[]
    //如果有值,进行decode(编码,从一个string转换为一个json)
    var tamp = cartString == null ? [] : json.decode(cartString!);
    //把获取到的json转换为一个list
    List<Map> tampList = (tamp as List).cast();

    //当前购物车中是否存在该商品,通过goodId来判断
    var isHave = false;
    int i = 0; //用于循环的int
    allGoodsCount = 0;
    for (var element in tampList) {
      //进行循环,找出是否已经存在该商品,如果存在,进行数量+1,注意,临时list需要+1,数据源list也需要+1
      if (element['goodsId'] == goodsId) {
        tampList[i]['count'] = element['count'] + 1;
        cartList[i].count = cartList[i].count! + 1;
        isHave = true;
      }

      if(element['isCheck']){
        allGoodsCount += cartList[i].count!;
        setAllGoodsCount(allGoodsCount);
      }
      i++;
    }

    //判断如果数据源中没有当前商品,则添加一个商品到list中和数据源中
    if (!isHave) {
      Map<String, dynamic> newGood = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'imagesUrl': imageUrl,
        'isCheck': isCheck
      };
      tampList.add(newGood);
      cartList.add(CartInfoBeanResult.fromJson(newGood));
    }

    //数据操作完毕,把tampList转换为一个String再保存到sp中
    cartString = json.encode(tampList).toString();
    sharedPreferences.setString(spKey, cartString!);
    notifyListeners();
  }

  //清空购物车sp中的数据
  remove() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.remove(spKey);
    cartList.clear();
    notifyListeners();
  }

  //拿到sp中购物车的数据
  getCartInfo() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //得到购物车中所有商品,此时是一个字符串(json形式)
    cartString = sharedPreferences.getString(spKey);
    //将cartList清空,防止重复进入购物车页面时数据不匹配
    cartList = [];
    if (cartString == null) {
      cartList = [];
    } else {
      List<Map<String, dynamic>> tempList =
          (json.decode(cartString.toString()) as List).cast();
      isAllCheck = true;
      allPrice = 0;
      allGoodsCount = 0;
      for (var element in tempList) {
        if (element['isCheck']) {
          allPrice += element['count']*element ['price'];
          allGoodsCount += element['count'];
        } else {
          isAllCheck = false;
        }
        cartList.add(CartInfoBeanResult.fromJson(element));
      }
    }
    notifyListeners();
  }

  //修改单个item选中的状态
  changeCheckState(CartInfoBeanResult cartInfoBeanResult) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString(spKey);
    List<Map> tempList =
        (json.decode(cartString.toString()) as List).cast(); //从sp中取出的list

    int tempIndex = 0; //用于循环的list下标
    int changeIndex = 0; //保存找到对应商品的下标

    for (var element in tempList) {
      if (element['goodsId'] == cartInfoBeanResult.goodsId) {
        changeIndex = tempIndex;
      }
      tempIndex++;
    }
    tempList[changeIndex] = cartInfoBeanResult.toJson(); //把当前传入的对象转换为json进行赋值
    cartString = json.encode(tempList).toString(); //把临时的list转换为json用于保存
    sharedPreferences.setString(spKey, cartString!);
    await getCartInfo();
  }

  //全选按钮的状态改变
  changeAllCheckBtnState(bool isCheck) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString(spKey);
    List<Map> tempList =
        (json.decode(cartString.toString()) as List).cast(); //从sp中取出的list
    List<Map> newList = []; //用于组成新的持久化数据
    for (var item in tempList) {
      var newItem = item; //赋值新的变量,因为Dart不让再循环时修改原值
      newItem['isCheck'] = isCheck; //通过参数给原有的bean中的选中属性赋值
      newList.add(newItem);
    }

    cartString = json.encode(newList).toString(); //把临时的list转换为json用于保存
    sharedPreferences.setString(spKey, cartString!);
    await getCartInfo();
  }

  deleteOneGood(int goodsId) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString(spKey);
    List<Map> tempList =
        (json.decode(cartString.toString()) as List).cast(); //从sp中取出的list

    int tempIndex = 0; //用于循环的index
    int deleteIndex = 0; //用于删除的index

    for (var element in tempList) {
      if (element['goodsId'] == goodsId) {
        deleteIndex = tempIndex;
      }
      tempIndex++;
    }
    tempList.removeAt(deleteIndex); //通过下标来删除集合中的某一个元素

    cartString = json.encode(tempList).toString(); //把临时的list转换为json用于保存
    sharedPreferences.setString(spKey, cartString!);
    await getCartInfo();
  }

  //加减购物车item数量的操作
  addOrReduceAction(CartInfoBeanResult item, String todo) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString(spKey);
    List<Map> tempList =
        (json.decode(cartString.toString()) as List).cast(); //从sp中取出的list

    int tempIndex = 0; //用于循环的index
    int changeIndex = 0; //用于加减的index

    for (var element in tempList) {
      if (element['goodsId'] == item.goodsId) {
        changeIndex = tempIndex;
      }
      tempIndex++;
    }

    if (todo == 'add') {
      item.count = item.count! + 1;
    } else if (item.count! > 1) {
      //减法,必须得满足数量大于1,小于1则不作操作
      item.count = item.count! - 1;
    }

    tempList[changeIndex] = item.toJson();

    cartString = json.encode(tempList).toString(); //把临时的list转换为json用于保存
    sharedPreferences.setString(spKey, cartString!);
    await getCartInfo();
  }

  setAllGoodsCount(count){
    allGoodsCount = count;
    notifyListeners();
  }
}
